package com.emagic.manage.modules.room.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.emagic.manage.LifeApplication;
import com.emagic.manage.R;
import com.emagic.manage.R2;
import com.emagic.manage.common.ui.base.ToolBarActivity;
import com.emagic.manage.modules.room.adapter.CommentListAdapter;
import com.emagic.manage.modules.room.adapter.CoursewareAdapter;
import com.emagic.manage.modules.room.adapter.InClassUserListAdapter;
import com.emagic.manage.modules.room.adapter.VideoAdapter;
import com.emagic.manage.modules.room.presenter.SendGiftPresenter;
import com.emagic.manage.modules.room.view.AllRoomUser;
import com.emagic.manage.modules.room.view.ClassRoomManager;
import com.emagic.manage.modules.room.view.ClassRoomUser;
import com.emagic.manage.modules.room.view.GiftsView;
import com.emagic.manage.modules.room.view.IClassRoomManagerCbk;
import com.emagic.manage.modules.room.view.RoomFile;
import com.emagic.manage.utils.DisplayUtil;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.xitaiinfo.library.commons.rx.Rx;
import com.xitaiinfo.library.utils.ViewUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.webrtc.EglBase;
import org.webrtc.SurfaceViewRenderer;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;

import static java.lang.String.valueOf;

/**
 * 教师课堂
 * Created by xiatian on 2017/11/1.
 */

public class TRoomActivityOne extends ToolBarActivity implements IClassRoomManagerCbk, GiftsView {
    private static String TAG = "TRoomActivityOne";
    private static final String SERIAL = "serial";             //课堂标示
    private static final String CHAIRMANPWD = "chairmanpwd";   //教师密码
    private static final String CONFUSERPWD = "confuserpwd";   //学生密码
    private static final String CLASSNAME = "classname";   //学生密码

    @BindView(R2.id.toolbar_layout)
    RelativeLayout mToolBarLayout;
    @BindView(R2.id.back_btn)
    TextView mBackBtn;
    @BindView(R2.id.room_name)
    TextView mRoomName;
    @BindView(R2.id.up_head_btn)
    TextView mUpHeadBtn;
    @BindView(R2.id.time_text)
    Chronometer mTimeText;

    @BindView(R2.id.user_action_layout)
    LinearLayout mUserActionLayout;
    @BindView(R2.id.courseware_btn)
    ImageView mCoursewareBtn;
    @BindView(R2.id.courseware_layout)
    LinearLayout mCoursewareLayout;
    @BindView(R2.id.courseware_title)
    TextView mCoursewareTitle;
    @BindView(R2.id.white_box)
    ImageView mWhiteBox;
    @BindView(R2.id.courseware_list)
    RecyclerView mCoursewareList;
    @BindView(R2.id.add_courseware)
    TextView mAddCourseware;

    @BindView(R2.id.video_btn)
    ImageView mVideoBtn;
    @BindView(R2.id.video_layout)
    LinearLayout mVideoLayout;
    @BindView(R2.id.video_title)
    TextView mVideoTitle;
    @BindView(R2.id.video_list)
    RecyclerView mVideoList;
    @BindView(R2.id.add_video)
    TextView mAddVideo;

    @BindView(R2.id.users_btn)
    ImageView mUsersBtn;
    @BindView(R2.id.users_layout)
    LinearLayout mUsersLayout;
    @BindView(R2.id.users_title)
    TextView mUsersTitle;
    @BindView(R2.id.users_list)
    RecyclerView mUsersList;

    @BindView(R2.id.left_layout)
    LinearLayout mLeftLayout;
    @BindView(R2.id.web_layout)
    RelativeLayout mWebLayout;
    @BindView(R2.id.show_view)
    WebView mShowView;
    @BindView(R2.id.send_gifts_img)
    ImageView mSendGiftsImg;

    @BindView(R2.id.video_show_layout)
    LinearLayout mVideoShowLayout;
    @BindView(R2.id.video_view_layout)
    RelativeLayout mVideoViewLayout;
    @BindView(R2.id.video_view)
    VideoView mVideoView;
    @BindView(R2.id.action_bar)
    ImageView mActionBar;
    @BindView(R2.id.seek_bar)
    SeekBar mSeekBar;
    @BindView(R2.id.closed_btn)
    TextView mClosedBtn;
    @BindView(R2.id.time_change_text)
    TextView mTimeChangeTV;
    @BindView(R2.id.seekBar_volume)
    SeekBar mSeekBarVolume;
    @BindView(R2.id.audio_closed)
    ImageView mAudioClosed;
    @BindView(R2.id.audio_name)
    TextView mAudioName;
    @BindView(R2.id.enlarge_btn)
    ImageView mEnlargeBtn;

    @BindView(R2.id.teacher_show_layout)
    LinearLayout mTSLayout;
    @BindView(R2.id.right_layout)
    LinearLayout mRightLayout;
    @BindView(R2.id.teacher_layout)
    RelativeLayout mTeacherLayout;
    @BindView(R2.id.surfaceViewTeacher)
    SurfaceViewRenderer mSurfaceViewTeacher;
    @BindView(R2.id.teacher_name)
    TextView mTeacherName;
    @BindView(R2.id.teacher_action_layout)
    LinearLayout mTeacherActionLayout;
    @BindView(R2.id.voice_action)
    TextView mVoiceAction;
    @BindView(R2.id.video_action)
    TextView mVideoAction;
    @BindView(R2.id.change_action)
    TextView mChangeAction;

    @BindView(R2.id.student_show_layout)
    LinearLayout mSSLayout;
    @BindView(R2.id.student_layout)
    RelativeLayout mStudentLayout;
    @BindView(R2.id.surfaceViewStudent)
    SurfaceViewRenderer mSurfaceViewStudent;
    @BindView(R2.id.student_name)
    TextView mStudentName;
    @BindView(R2.id.student_action_layout)
    LinearLayout mStudentActionLayout;
    @BindView(R2.id.draw_action_student)
    TextView mDrawActionStudent;
    @BindView(R2.id.voice_action_student)
    TextView mVoiceActionStudent;
    @BindView(R2.id.change_action_student)
    TextView mChangeActionStudent;

    @BindView(R2.id.comm_layout)
    LinearLayout mCommLayout;
    @BindView(R2.id.comm_list)
    RecyclerView mCommList;
    @BindView(R2.id.say_edt)
    EditText mSayEdt;
    @BindView(R2.id.push_btn)
    TextView mPushBtn;

    @BindView(R2.id.answer_layout)
    RelativeLayout mAnswerLayout;
    @BindView(R2.id.answer_img)
    ImageView mAnswerImg;
    @BindView(R2.id.answer_text)
    TextView mAnswerText;
    @BindView(R2.id.start_answer)
    TextView mStartAnswer;
    @BindView(R2.id.stop_answer)
    TextView mStopAnswer;
    @BindView(R2.id.answer_message_layout)
    LinearLayout mAnswerMsgLayout;
    @BindView(R2.id.answer_message)
    TextView mAnswerMsg;

    @Inject
    SendGiftPresenter mSendGiftPresenter;

    private String serial, chairmanpwd, confuserpwd, classname, teacherId, showPeerid;

    private CommentListAdapter mAdapter;

    private InClassUserListAdapter mInClassAdapter;

    private CoursewareAdapter mCoursewareAdapter;

    private VideoAdapter mVideoAdapter;

    private StringBuilder mFormatBuilder;
    private Formatter mFormatter;

    private int rightViewHeight, rightViewWidth;

    private TranslateAnimation alphaAnimation2;

    private List<RoomFile> CoursewareList = new ArrayList<>();
    private List<RoomFile> VideoList = new ArrayList<>();

    private boolean pageFinished = false;
    private String mediaType = "";

    private boolean isWhiteBox = true;
    private boolean isBackPlay = false;
    private boolean isVoicePlay = true;
    private boolean isVideoPlay = true;
    private boolean isBackPlays = false;
    private boolean isVoicePlay1 = true;
    private boolean isDrawPlay1 = true;
    private boolean isRePlaying = false;

    private boolean isClassBegin;
    private long classStarTime = 0, classEndTime = 0, seveiceTime = 0, localTime = 0;
    private String answerOrPlay = "1";//1抢答 2掷骰子 3送礼物
    private String receiveGiftsId = "";
    private AlertDialog alertDialog = null;
    private ProgressDialog progressDialog = null;
    private AudioManager audioManager;
    private MediaPlayer player = new MediaPlayer();

    private boolean isPlaying = true;

    private List<AllRoomUser.RoomUser> allRoomUserList = new ArrayList<>();

    private List<AllRoomUser.RoomUser> recUserList = new ArrayList<>();

    private List<AllRoomUser.RoomUser> inClassUserList = new ArrayList<>();

    private RoomFile video;
    private RoomFile cours;

    private int maxVolume, syscurrenvolume;
    private RequestParams param;

    public static Intent getCallingIntent(Context context, String serial, String chairmanpwd,
                                          String confuserpwd, String classname) {

        Intent intent = new Intent(context, TRoomActivityOne.class);
        intent.putExtra(SERIAL, serial);
        intent.putExtra(CHAIRMANPWD, chairmanpwd);
        intent.putExtra(CONFUSERPWD, confuserpwd);
        intent.putExtra(CLASSNAME, classname);
        return intent;
    }

    public static void removeOnGlobalLayoutListener(View view, ViewTreeObserver.OnGlobalLayoutListener victim) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            view.getViewTreeObserver().removeOnGlobalLayoutListener(victim);
        } else {
            view.getViewTreeObserver().removeGlobalOnLayoutListener(victim);
        }
    }

    private void initView() {
        mSurfaceViewTeacher.init(EglBase.create().getEglBaseContext(), null);

        mFormatBuilder = new StringBuilder();
        mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());

        mSSLayout.setVisibility(View.VISIBLE);
        mUsersBtn.setVisibility(View.GONE);

        int screenWidth = DisplayUtil.getScreenWidth(this);
        int screenHeight = DisplayUtil.getScreenHeight(this);
        double screenH2W = (double) screenHeight / (double) screenWidth;
        ViewTreeObserver viewTreeObserver = mTSLayout.getViewTreeObserver();
        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @SuppressWarnings("deprecation")
            @Override
            public void onGlobalLayout() {
                removeOnGlobalLayoutListener(mTSLayout, this);
                rightViewWidth = mTSLayout.getWidth();
                rightViewHeight = (int) (rightViewWidth * screenH2W);
                mTSLayout.setLayoutParams(new LinearLayout.LayoutParams(rightViewWidth, rightViewHeight));
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(rightViewWidth, rightViewHeight);
                int margin = ViewUtils.dip2px(TRoomActivityOne.this, 10);
                layoutParams.setMargins(margin, margin, margin, 0);
                mSSLayout.setLayoutParams(layoutParams);
            }
        });


        //进度条绑定最大音量，最大音量
        mSeekBarVolume.setMax(maxVolume);
        //进度条绑定当前音量
        mSeekBarVolume.setProgress(syscurrenvolume);
        mSeekBarVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //取得当前进度
                int tmpInt = seekBar.getProgress();

                // 当进度小于1时，设置成1，防止太小。
                if (tmpInt < 1) {
                    tmpInt = 1;
                }

                // 根据当前进度改变亮度
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, tmpInt, 0);
            }
        });

        mShowView.getSettings().setJavaScriptEnabled(true);
        mShowView.addJavascriptInterface(new AndroidBridge(), "JSWhitePadInterface"); //将那个实例化的函数类设置为”android"的js接口。
        //启用数据
        mShowView.getSettings().setDatabaseEnabled(true);
        //启用地理定位
        mShowView.getSettings().setGeolocationEnabled(true);
        //开启DomStorage缓存
        mShowView.getSettings().setDomStorageEnabled(true);
        mShowView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mShowView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mShowView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mShowView.getSettings().setDefaultTextEncodingName("utf_8");
        mShowView.loadUrl("https://www.weiyiclass.com/static/pad_demo/index.html");
        mShowView.setWebViewClient(new WebViewClient() {

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();// 接受所有网站的证书
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                view.loadUrl("javascript:GLOBAL.phone.setInitPageParameterFormPhone({\n" +
                        "        \"roomrole\" : 0, \n" +
                        "        \"mClientType\" : 3,\n" +
                        "        \"roomtype\" : 0,\n" +
                        "        \"serviceUrl\" : {\n" +
                        "            \"address\" : \"https://www.weiyiclass.com\",\n" +
                        "            \"port\" : 443\n" +
                        "        }\n" +
                        "    });");

                view.loadUrl("javascript:GLOBAL.phone.drawPermission(true)");

                pageFinished = true;
                afterPageFinished();
            }
        });

        mInClassAdapter = new InClassUserListAdapter(new ArrayList<>(0));
        mUsersList.setLayoutManager(new LinearLayoutManager(this));
        mUsersList.setAdapter(mInClassAdapter);

        mCoursewareAdapter = new CoursewareAdapter(new ArrayList<>(0));
        mCoursewareList.setLayoutManager(new LinearLayoutManager(this));
        mCoursewareList.setAdapter(mCoursewareAdapter);

        mVideoAdapter = new VideoAdapter(new ArrayList<>(0));
        mVideoList.setLayoutManager(new LinearLayoutManager(this));
        mVideoList.setAdapter(mVideoAdapter);

    }

    private void afterPageFinished() {
        showLoadDialog();
        param = new RequestParams();
        param.put("serial", serial);
        param.put("userid", LifeApplication.getInstance().getCurrentUser().getUserid());
        param.put("userrole", LifeApplication.getInstance().getCurrentUser().getUserroleid());
        if ("0".equals(LifeApplication.getInstance().getCurrentUser().getUserroleid())) {
            param.put("password", chairmanpwd);
        } else {
            param.put("password", confuserpwd);
        }

        Log.e("param", param.toString());

        Log.e(TAG, "Start!");
        ClassRoomManager.globalInitialize(getContext());
        ClassRoomManager.getInstance().setCallbBack(this);
        ClassRoomManager.getInstance().joinRoom("media01.weiyiclass.com",
//                "edu.weiyicloud.com", "8443", "443",
                "www.weiyiclass.com", "8443", "443",
                LifeApplication.getInstance().getCurrentUser().getFirstname(),
                param, mSurfaceViewTeacher, true, "teacher");
        mTimeText.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer chronometer) {

                if (chronometer.getText().equals("")) {
                }
            }
        });
    }

    private void showLoadDialog() {
        if (null == progressDialog) {
            progressDialog = ProgressDialog.show(TRoomActivityOne.this, "", "准备上课，请稍候...");
            progressDialog.setCancelable(true);
        } else {
            progressDialog.show();
        }
    }

    private void dismissLoadDialog() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_t_room_one);
        ButterKnife.bind(this);
        getToolbar().setVisibility(View.GONE);
        serial = getIntent().getStringExtra(SERIAL);
        chairmanpwd = getIntent().getStringExtra(CHAIRMANPWD);
        confuserpwd = getIntent().getStringExtra(CONFUSERPWD);
        classname = getIntent().getStringExtra(CLASSNAME);
        mSendGiftPresenter.attachView(this);
        //获取音频服务
        audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        //设置声音模式
        audioManager.setMode(AudioManager.STREAM_MUSIC);
        //取得最大音量
        maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        //取得当前音量
        syscurrenvolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        isClassBegin = false;
        initView();
        initAction();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSendGiftPresenter.onDestroy();
        if (player != null) {
            player.stop();
        }
        if (mVideoView != null) {
            mVideoView.stopPlayback();
        }
    }

    private void initAction() {
        Rx.click(mBackBtn, 1000, v -> {
            if (!isClassBegin) {
                ClassRoomManager.getInstance().set_status(0);
                this.finish();
            } else {
                showLeaveDialog();
            }
        });

        mRoomName.setText(classname);

        Rx.click(mUpHeadBtn, 1000, v -> {//上课
            if (pageFinished) {
                if (!isClassBegin) {
                    sendClassBegin();
                } else {
                    showLeaveDialog();
                }
            }
        });

        Rx.click(mPushBtn, 1000, v -> {//发言
            if (isClassBegin) {
                if (!TextUtils.isEmpty(mSayEdt.getText().toString().trim())) {
                    ClassRoomManager.getInstance().sendMessage(mSayEdt.getText().toString().trim());
                } else {
                    Toast.makeText(this, "发送内容不能为空", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "课程还没有开始", Toast.LENGTH_SHORT).show();
            }
        });

        Rx.click(mStartAnswer, 1000, v -> {
            if (inClassUserList != null && inClassUserList.size() > 0) {
                mStartAnswer.setEnabled(false);
                HashMap<String, Object> data = new HashMap<>();
                HashMap<String, Object> params = new HashMap<>();
                ArrayList<Map<String, Object>> stus = new ArrayList<>();
                for (int i = 0; i < inClassUserList.size(); i++) {
                    Map<String, Object> stu = new HashMap<>();
                    stu.put("id", inClassUserList.get(i).getReceiveid());
                    stu.put("num", 1 + (int) (Math.random() * 6));
                    stus.add(stu);
                }
                if ("1".equals(answerOrPlay)) {//开始抢答
                    params.put("id", "startAnswer");
                    params.put("name", "startAnswer");
                } else if ("2".equals(answerOrPlay)) {//开始掷骰子
                    params.put("id", "playDice");
                    params.put("name", "playDice");
                    data.put("isShowDice", true);
                    data.put("stus", stus);
                } else if ("3".equals(answerOrPlay)) {//送礼物
                    mStartAnswer.setEnabled(true);
                    givingGifts(receiveGiftsId);
                    return;
                }
                params.put("toID", "__all");
                params.put("data", data);

                ClassRoomManager.getInstance().pubMsg(params);
            } else {
                mAnswerLayout.setVisibility(View.GONE);
            }
        });

        Rx.click(mStopAnswer, 1000, v -> {
            mStartAnswer.setEnabled(true);
            HashMap<String, Object> data = new HashMap<>();
            HashMap<String, Object> params = new HashMap<>();
            if ("1".equals(answerOrPlay)) {//取消抢答
                params.put("id", "stopAnswer");
                params.put("name", "stopAnswer");
            } else if ("2".equals(answerOrPlay)) {//取消掷骰子
                params.put("id", "playDice");
                params.put("name", "playDice");
                data.put("isShowDice", false);
            } else if ("3".equals(answerOrPlay)) {//取消送礼物
                mAnswerMsgLayout.setVisibility(View.GONE);
                mAnswerText.setVisibility(View.GONE);
                mAnswerImg.setVisibility(View.VISIBLE);
                mAnswerLayout.setVisibility(View.GONE);
                return;
            }
            params.put("toID", "__all");
            params.put("data", data);

            ClassRoomManager.getInstance().delMsg(params);
        });

        Rx.click(mCoursewareBtn, 1000, v -> {
            mVideoLayout.setVisibility(View.GONE);
            mUsersLayout.setVisibility(View.GONE);
            mVideoBtn.setBackgroundResource(R.color.left_bg);
            mUsersBtn.setBackgroundResource(R.color.left_bg);
            if (mCoursewareLayout.getVisibility() == View.GONE) {
                mCoursewareLayout.setVisibility(View.VISIBLE);
                mCoursewareBtn.setBackgroundResource(R.color.comm_item_line);
            } else if (mCoursewareLayout.getVisibility() == View.VISIBLE) {
                mCoursewareLayout.setVisibility(View.GONE);
                mCoursewareBtn.setBackgroundResource(R.color.left_bg);
            }

        });

        Rx.click(mVideoBtn, 1000, v -> {
            mCoursewareLayout.setVisibility(View.GONE);
            mUsersLayout.setVisibility(View.GONE);
            mCoursewareBtn.setBackgroundResource(R.color.left_bg);
            mUsersBtn.setBackgroundResource(R.color.left_bg);
            if (mVideoLayout.getVisibility() == View.GONE) {
                mVideoLayout.setVisibility(View.VISIBLE);
                mVideoBtn.setBackgroundResource(R.color.comm_item_line);
            } else if (mVideoLayout.getVisibility() == View.VISIBLE) {
                mVideoLayout.setVisibility(View.GONE);
                mVideoBtn.setBackgroundResource(R.color.left_bg);
            }
        });

        Rx.click(mUsersBtn, 1000, v -> {
            mCoursewareLayout.setVisibility(View.GONE);
            mVideoLayout.setVisibility(View.GONE);
            mCoursewareBtn.setBackgroundResource(R.color.left_bg);
            mVideoBtn.setBackgroundResource(R.color.left_bg);
            if (mUsersLayout.getVisibility() == View.GONE) {
                mUsersLayout.setVisibility(View.VISIBLE);
                mUsersBtn.setBackgroundResource(R.color.comm_item_line);
            } else if (mUsersLayout.getVisibility() == View.VISIBLE) {
                mUsersLayout.setVisibility(View.GONE);
                mUsersBtn.setBackgroundResource(R.color.left_bg);
            }
        });

        Rx.click(mWhiteBox, 1000, v -> {
            mCoursewareLayout.setVisibility(View.GONE);
            mVideoLayout.setVisibility(View.GONE);
            mUsersLayout.setVisibility(View.GONE);
            mCoursewareBtn.setBackgroundResource(R.color.left_bg);
            mVideoBtn.setBackgroundResource(R.color.left_bg);
            mUsersBtn.setBackgroundResource(R.color.left_bg);
            for (int i = 0; i < CoursewareList.size(); i++) {
                CoursewareList.get(i).setState("0");
            }
            mCoursewareAdapter.notifyDataSetChanged();
            int fileid = 0;
            if (isWhiteBox) {
                if (cours != null) {
                    fileid = Integer.parseInt(cours.getFileid());
                    for (int i = 0; i < CoursewareList.size(); i++) {
                        if (cours.getFileid().equals(CoursewareList.get(i).getFileid())) {
                            cours.setState("1");
                            CoursewareList.remove(i);
                            CoursewareList.add(i, cours);
                            mCoursewareAdapter.setNewData(CoursewareList);
                            isWhiteBox = false;
                            break;
                        }
                    }
                } else {
                    return;
                }
            } else {
                isWhiteBox = true;
            }
            HashMap<String, Object> filedata = new HashMap<>();
            filedata.put("fileid", fileid);
            filedata.put("filename", cours.getFilename());
            filedata.put("filetype", cours.getFiletype());
            filedata.put("isconvert", cours.getIsconvert());
            filedata.put("pagenum", cours.getPagenum());
            filedata.put("swfpath", cours.getSwfpath());

            HashMap<String, Object> data = new HashMap<>();
            data.put("filedata", filedata);
            data.put("fileid", fileid);
            data.put("ismedia", false);
            data.put("page", 1);

            HashMap<String, Object> params = new HashMap<>();
            params.put("id", "DocumentFilePage_ShowPage");
            params.put("name", "ShowPage");
            params.put("toID", "__allExceptSender");
            params.put("data", data);

            ClassRoomManager.getInstance().pubMsg(params);

            JSONObject changeData = new JSONObject();
            try {
                changeData.put("data_file_name", cours.getFilename());
                changeData.put("data_file_type", cours.getFiletype());
                changeData.put("data_file_ismedia", false);
                changeData.put("data_file_swfpath", cours.getSwfpath());
                changeData.put("data_file_id", fileid);
                changeData.put("data_curr_page", 1);
                changeData.put("data_total_page", 1);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.d(TAG, "roomManagerOnRemoteMsgUrl: " + "javascript:GLOBAL.phone.receivePhoneByTriggerEvent(" + "\"openCourse-message-received\"" + ", " + changeData + ")");
            mShowView.loadUrl("javascript:GLOBAL.phone.receivePhoneByTriggerEvent(" + "\"openCourse-message-received\"" + ", " + changeData + ")");
        });

        Rx.click(mSurfaceViewTeacher, 1000, v -> {
            mTeacherActionLayout.setVisibility(View.VISIBLE);
            if (!isBackPlay) {
                mChangeAction.setText("全屏显示");
            } else {
                mChangeAction.setText("还原显示");
            }
            if (isVoicePlay) {
                mVoiceAction.setText("关闭音频");
            } else {
                mVoiceAction.setText("打开音频");
            }
            if (isVideoPlay) {
                mVideoAction.setText("关闭视频");
            } else {
                mVideoAction.setText("打开视频");
            }
        });
        Rx.click(mSurfaceViewStudent, 1000, v -> {
            mStudentActionLayout.setVisibility(View.VISIBLE);
            if (!isBackPlays) {
                mChangeActionStudent.setText("全屏显示");
            } else {
                mChangeActionStudent.setText("还原显示");
            }
            if (isVoicePlay1) {
                mVoiceActionStudent.setText("关闭音频");
            } else {
                mVoiceActionStudent.setText("打开音频");
            }
            if (isDrawPlay1) {
                mDrawActionStudent.setText("停止涂鸦");
            } else {
                mDrawActionStudent.setText("开始涂鸦");
            }
        });
        Rx.click(mTeacherActionLayout, 1000, v -> {
            mTeacherActionLayout.setVisibility(View.GONE);
        });
        Rx.click(mStudentActionLayout, 1000, v -> {
            mStudentActionLayout.setVisibility(View.GONE);
        });
        Rx.click(mVoiceAction, 1000, v -> {
            mTeacherActionLayout.setVisibility(View.GONE);
            if (isVoicePlay) {
                isVoicePlay = false;
                //关闭麦克风
                audioManager.setMicrophoneMute(true);
            } else {
                isVoicePlay = true;
                //打开麦克风
                audioManager.setMicrophoneMute(false);
            }
        });
        Rx.click(mVideoAction, 1000, v -> {
            mTeacherActionLayout.setVisibility(View.GONE);
            if (isVideoPlay) {
                isVideoPlay = false;
                ClassRoomManager.getInstance().enableVideo(false);
                mSurfaceViewTeacher.release();
            } else {
                isVideoPlay = true;
                mSurfaceViewTeacher.init(EglBase.create().getEglBaseContext(), null);
                ClassRoomManager.getInstance().enableVideo(true);
            }
        });
        Rx.click(mChangeAction, 1000, v -> {
            mTeacherActionLayout.setVisibility(View.GONE);
            if (!isBackPlay) {
                mToolBarLayout.setVisibility(View.GONE);
                mUserActionLayout.setVisibility(View.GONE);
                mSSLayout.setVisibility(View.GONE);
                mSurfaceViewStudent.setVisibility(View.GONE);
                mLeftLayout.setVisibility(View.GONE);
                mCommLayout.setVisibility(View.GONE);

                isBackPlay = true;
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mTSLayout.getLayoutParams();
                lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
                lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
                lp.setMargins(0, 0, 0, 0);
                mTSLayout.setLayoutParams(lp);


            } else {
                mToolBarLayout.setVisibility(View.VISIBLE);
                mUserActionLayout.setVisibility(View.VISIBLE);
                mSSLayout.setVisibility(View.VISIBLE);
                mSurfaceViewStudent.setVisibility(View.VISIBLE);
                mLeftLayout.setVisibility(View.VISIBLE);
                mCommLayout.setVisibility(View.VISIBLE);

                isBackPlay = false;
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mTSLayout.getLayoutParams();
                lp.height = rightViewHeight;
                lp.width = rightViewWidth;
                int margin = ViewUtils.dip2px(TRoomActivityOne.this, 10);
                lp.setMargins(margin, 0, margin, 0);
                mTSLayout.setLayoutParams(lp);
            }
        });

        Rx.click(mDrawActionStudent, 1000, v -> {
            mStudentActionLayout.setVisibility(View.GONE);
            HashMap<String, Object> property = new HashMap<>();
            if (!isDrawPlay1) {
                isDrawPlay1 = true;
                property.put("candraw", true);
            } else if (isDrawPlay1) {//关闭涂鸦
                isDrawPlay1 = false;
                property.put("candraw", false);
            }
            ClassRoomManager.getInstance().changeUserProperty(inClassUserList.get(0).getReceiveid(), "__all", property);
        });

        Rx.click(mVoiceActionStudent, 1000, v -> {
            mStudentActionLayout.setVisibility(View.GONE);
            if (!isVoicePlay1) {//关闭语言
                isVoicePlay1 = true;
                ClassRoomManager.getInstance().changeUserPublish(inClassUserList.get(0).getReceiveid(), 2);
            } else if (isVoicePlay1) {//开启语言
                isVoicePlay1 = false;
                ClassRoomManager.getInstance().changeUserPublish(inClassUserList.get(0).getReceiveid(), 3);
            }
        });

        Rx.click(mChangeActionStudent, 1000, v -> {
            mStudentActionLayout.setVisibility(View.GONE);
            if (!isBackPlays) {

                mToolBarLayout.setVisibility(View.GONE);
                mUserActionLayout.setVisibility(View.GONE);
                mTSLayout.setVisibility(View.GONE);
                mSurfaceViewTeacher.setVisibility(View.GONE);
                mLeftLayout.setVisibility(View.GONE);
                mCommLayout.setVisibility(View.GONE);

                isBackPlays = true;
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mSSLayout.getLayoutParams();
                lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
                lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
                lp.setMargins(0, 0, 0, 0);
                mSSLayout.setLayoutParams(lp);


            } else {
                mToolBarLayout.setVisibility(View.VISIBLE);
                mUserActionLayout.setVisibility(View.VISIBLE);
                mTSLayout.setVisibility(View.VISIBLE);
                mSurfaceViewTeacher.setVisibility(View.VISIBLE);
                mLeftLayout.setVisibility(View.VISIBLE);
                mCommLayout.setVisibility(View.VISIBLE);

                isBackPlays = false;
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mSSLayout.getLayoutParams();
                lp.height = rightViewHeight;
                lp.width = rightViewWidth;
                int margin = ViewUtils.dip2px(TRoomActivityOne.this, 10);
                lp.setMargins(margin, margin, margin, 0);
                mSSLayout.setLayoutParams(lp);
            }
        });
        Rx.click(mEnlargeBtn, 1000, v -> {
            if (!isBackPlay) {
                isBackPlay = true;
                mToolBarLayout.setVisibility(View.GONE);
                mUserActionLayout.setVisibility(View.GONE);
                mRightLayout.setVisibility(View.GONE);
                mUsersLayout.setVisibility(View.GONE);
                mVideoLayout.setVisibility(View.GONE);
                mCoursewareLayout.setVisibility(View.GONE);

            } else {
                isBackPlay = false;
                mToolBarLayout.setVisibility(View.VISIBLE);
                mUserActionLayout.setVisibility(View.VISIBLE);
                mRightLayout.setVisibility(View.VISIBLE);
                mUsersLayout.setVisibility(View.VISIBLE);
                mVideoLayout.setVisibility(View.VISIBLE);
                mCoursewareLayout.setVisibility(View.VISIBLE);
            }
        });

        mCommList.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                AllRoomUser.RoomUser user = (AllRoomUser.RoomUser) adapter.getItem(position);
                HashMap<String, Object> property = new HashMap<>();
                int i = view.getId();
                if (i == R.id.disagree) {
                    user.setHeadup(false);
                    user.setShow(false);
                    recUserList.remove(position);
                    recUserList.add(user);
                    mAdapter.setNewData(recUserList);
                    property.put("raisehand", false);
                    ClassRoomManager.getInstance().changeUserProperty(user.getReceiveid(), "__all", property);
                    ClassRoomManager.getInstance().changeUserPublish(user.getReceiveid(), 0);

                } else if (i == R.id.agree) {
                    user.setHeadup(true);
                    user.setShow(false);
                    recUserList.remove(position);
                    recUserList.add(user);
                    mAdapter.setNewData(recUserList);
                    property.put("raisehand", false);
                    ClassRoomManager.getInstance().changeUserProperty(user.getReceiveid(), "__all", property);
                    ClassRoomManager.getInstance().changeUserPublish(user.getReceiveid(), 3);

                }
            }
        });

        mUsersList.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                AllRoomUser.RoomUser user = (AllRoomUser.RoomUser) adapter.getItem(position);
                int i = view.getId();
                if (i == R.id.video_img) {
                    if (user.getState() == ClassRoomUser.PUBLISH_STATE_NONE) {//开始上台功能
                        user.setState(3);
                        HashMap<String, Object> property = new HashMap<>();
                        property.put("candraw", false);
                        property.put("raisehand", false);
                        ClassRoomManager.getInstance().changeUserProperty(user.getReceiveid(), "__all", property);
                        ClassRoomManager.getInstance().changeUserPublish(user.getReceiveid(), 3);
                    } else {//下台
                        user.setState(0);
                        HashMap<String, Object> property = new HashMap<>();
                        property.put("candraw", false);
                        property.put("raisehand", false);
                        ClassRoomManager.getInstance().changeUserProperty(user.getReceiveid(), "__all", property);
                        ClassRoomManager.getInstance().changeUserPublish(user.getReceiveid(), 0);
                    }
                    adapter.notifyDataSetChanged();

                } else if (i == R.id.audio_img) {
                    if (user.getState() == ClassRoomUser.PUBLISH_STATE_BOTH) {//关闭语言
                        user.setState(2);
                        ClassRoomManager.getInstance().changeUserPublish(user.getReceiveid(), 2);
                    } else if (user.getState() == ClassRoomUser.PUBLISH_STATE_VIDEOONLY) {//开启语言
                        user.setState(3);
                        ClassRoomManager.getInstance().changeUserPublish(user.getReceiveid(), 3);
                    }
                    adapter.notifyDataSetChanged();

                } else if (i == R.id.draw_img) {
                    if (user.getState() != ClassRoomUser.PUBLISH_STATE_NONE && !user.isCandraw()) {
                        user.setCandraw(true);
                        HashMap<String, Object> property = new HashMap<>();
                        property.put("candraw", true);
                        ClassRoomManager.getInstance().changeUserProperty(user.getReceiveid(), "__all", property);
                    } else if (user.isCandraw()) {//关闭涂鸦
                        user.setCandraw(false);
                        HashMap<String, Object> property = new HashMap<>();
                        property.put("candraw", false);
                        ClassRoomManager.getInstance().changeUserProperty(user.getReceiveid(), "__all", property);
                    }
                    adapter.notifyDataSetChanged();

                }
            }
        });

        mCoursewareList.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                cours = (RoomFile) adapter.getItem(position);
                isWhiteBox = false;
                if (cours.getState().equals("0")) {//切换课件
                    for (int i = 0; i < CoursewareList.size(); i++) {
                        CoursewareList.get(i).setState("0");
                    }
                    mCoursewareAdapter.notifyDataSetChanged();
                    cours.setState("1");
                    CoursewareList.remove(position);
                    CoursewareList.add(position, cours);
                    mCoursewareAdapter.setNewData(CoursewareList);
                    HashMap<String, Object> filedata = new HashMap<>();
                    filedata.put("fileid", cours.getFileid());
                    filedata.put("filename", cours.getFilename());
                    filedata.put("filetype", cours.getFiletype());
                    filedata.put("isconvert", cours.getIsconvert());
                    filedata.put("pagenum", cours.getPagenum());
                    filedata.put("swfpath", cours.getSwfpath());

                    HashMap<String, Object> data = new HashMap<>();
                    data.put("filedata", filedata);
                    data.put("fileid", cours.getFileid());
                    data.put("ismedia", false);
                    data.put("page", 1);

                    HashMap<String, Object> params = new HashMap<>();
                    params.put("id", "DocumentFilePage_ShowPage");
                    params.put("name", "ShowPage");
                    params.put("toID", "__allExceptSender");
                    params.put("data", data);

                    ClassRoomManager.getInstance().pubMsg(params);

                    JSONObject changeData = new JSONObject();
                    try {
                        changeData.put("data_file_name", cours.getFilename());
                        changeData.put("data_file_type", cours.getFiletype());
                        changeData.put("data_file_ismedia", false);
                        changeData.put("data_file_swfpath", cours.getSwfpath());
                        changeData.put("data_file_id", cours.getFileid());
                        changeData.put("data_curr_page", cours.getIsconvert());
                        changeData.put("data_total_page", cours.getPagenum());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Log.d(TAG, "roomManagerOnRemoteMsgUrl: " + "javascript:GLOBAL.phone.receivePhoneByTriggerEvent(" + "\"openCourse-message-received\"" + ", " + changeData + ")");
                    mShowView.loadUrl("javascript:GLOBAL.phone.receivePhoneByTriggerEvent(" + "\"openCourse-message-received\"" + ", " + changeData + ")");
                }
            }
        });

        mVideoList.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                video = (RoomFile) adapter.getItem(position);
                stop();
                if (video.getState().equals("0")) {//开始演示视频
                    for (int i = 0; i < VideoList.size(); i++) {
                        VideoList.get(i).setState("0");
                    }
                    mVideoAdapter.notifyDataSetChanged();
                    video.setState("1");
                    VideoList.remove(position);
                    VideoList.add(position, video);
                    mVideoAdapter.setNewData(VideoList);
                    if (video.getFiletype().equals("mp4") || video.getFiletype().equals("webm")) {
                        mediaType = "video";
                    } else if (video.getFiletype().equals("mp3") || video.getFiletype().equals("wav") || video.getFiletype().equals("ogg")) {
                        mediaType = "audio";
                    }
                    showVideoView(video);
                }
            }
        });

        // 为进度条添加进度更改事件
        mSeekBar.setOnSeekBarChangeListener(change);

        Rx.click(mActionBar, 1000, v -> {
            if (mVideoShowLayout.getVisibility() == View.VISIBLE) {
                if (isRePlaying) {
                    isRePlaying = false;
                    replay();
                } else {
                    if (isPlaying) {//暂停
                        suspend();
                    } else {//继续
                        pause();
                    }
                }
            }
        });

        Rx.click(mClosedBtn, 1000, v -> {
            stop();
        });

        Rx.click(mAudioClosed, 1000, v -> {
            stop();
        });

    }

    private void sendClassBegin() {
        ClassRoomManager.getInstance().pubMsg("ClassBegin", "ClassBegin", "__all", null);
        HashMap<String, Object> property = new HashMap<>();
        property.put("publishstate", 3);
        ClassRoomManager.getInstance().changeUserProperty(ClassRoomManager.getInstance().getMySelf().peerId,
                "__all", property);
    }

    /**
     * 重新播放
     */
    private void replay() {
        if (mVideoView != null && mVideoView.isPlaying()) {
            mVideoView.seekTo(0);
            Toast.makeText(this, "重新播放", Toast.LENGTH_SHORT).show();
            mActionBar.setImageDrawable(getContext().getResources().getDrawable(R.mipmap.ic_play_bg));
            return;
        }
        isPlaying = false;
        showVideoView(video);
    }

    /**
     * 暂停播放
     */
    private void suspend() {
        isPlaying = false;
        if ("audio".equals(mediaType)) {
            player.pause();
        } else {
            mVideoView.pause();
        }

        mActionBar.setImageDrawable(getContext().getResources().getDrawable(R.mipmap.ic_play_bg));
        Toast.makeText(this, "暂停播放", Toast.LENGTH_SHORT).show();
        HashMap<String, Object> data = new HashMap<>();
        data.put("action", 0);
        data.put("currentTime", stringForSeconds(mSeekBar.getProgress()));
        data.put("fileid", video.getFileid());
        data.put("mediaType", mediaType);
        data.put("play", false);

        HashMap<String, Object> params = new HashMap<>();
        params.put("id", "MediaProgress_video_0");
        params.put("name", "MediaProgress");
        params.put("toID", "__allExceptSender");
        params.put("data", data);

        ClassRoomManager.getInstance().pubMsg(params);

    }

    /**
     * 继续播放
     */
    private void pause(int time) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                isPlaying = true;
                if ("audio".equals(mediaType)) {
                    if (player != null) {
                        player.start();
                        player.seekTo(time);
                    }
                } else {
                    mVideoView.start();
                    mVideoView.seekTo(time);
                }
                mActionBar.setImageDrawable(getContext().getResources().getDrawable(R.mipmap.ic_stop_bg));
                Toast.makeText(getContext(), "继续播放", Toast.LENGTH_SHORT).show();
                startNewThread();
            }
        });
    }

    /**
     * 继续播放
     */
    private void pause() {
        isPlaying = true;
        if ("audio".equals(mediaType)) {
            if (player != null) {
                player.start();
            }
        } else {
            mVideoView.start();
        }
        mActionBar.setImageDrawable(getContext().getResources().getDrawable(R.mipmap.ic_stop_bg));
        startNewThread();
        Toast.makeText(this, "继续播放", Toast.LENGTH_SHORT).show();
        HashMap<String, Object> data = new HashMap<>();
        data.put("action", 0);
        data.put("currentTime", stringForSeconds(mSeekBar.getProgress()));
        data.put("fileid", video.getFileid());
        data.put("mediaType", mediaType);
        data.put("play", true);

        HashMap<String, Object> params = new HashMap<>();
        params.put("id", "MediaProgress_video_0");
        params.put("name", "MediaProgress");
        params.put("toID", "__allExceptSender");
        params.put("data", data);

        ClassRoomManager.getInstance().pubMsg(params);
    }

    /**
     * 停止播放
     */
    private void stop() {
        isPlaying = false;
        mVideoShowLayout.setVisibility(View.GONE);
        if (player == null && mVideoView == null) {
            return;
        } else {
            if ("audio".equals(mediaType)) {
                if (player != null) {
                    player.stop();
                }
            } else {
                if (mVideoView != null && mVideoView.isPlaying()) {
                    mVideoView.stopPlayback();
                }
            }
            for (int i = 0; i < VideoList.size(); i++) {
                VideoList.get(i).setState("0");
            }
            mVideoAdapter.setNewData(VideoList);
            HashMap<String, Object> data = new HashMap<>();
            data.put("ismedia", true);
            data.put("fileid", video.getFileid());
            data.put("mediaType", mediaType);

            HashMap<String, Object> params = new HashMap<>();
            if ("audio".equals(mediaType)) {
                params.put("id", "Audio_MediaFilePage_ShowPage");
            } else {
                params.put("id", "Video_MediaFilePage_ShowPage");
            }
            params.put("name", "ShowPage");
            params.put("toID", "__allExceptSender");
            params.put("data", data);
            params.put("do_not_save", true);

            ClassRoomManager.getInstance().delMsg(params);
        }
    }

    /**
     * 播放视频文件
     *
     * @param file 视频文件
     */
    private void showVideoView(RoomFile file) {

        mVideoShowLayout.setVisibility(View.VISIBLE);
        String path = file.getSwfpath();
        if (!TextUtils.isEmpty(path) && path.contains(".")) {
            String[] strarray = path.split("\\.");
//            path = "http://edu.weiyicloud.com" + strarray[0] + "-1." + strarray[1];
            path = "http://www.weiyiclass.com" + strarray[0] + "-1." + strarray[1];
        }
        Uri uri = Uri.parse(path);
        Log.d("Uri=======", uri.toString());
        if ("audio".equals(mediaType)) {
            if (mVideoView != null) {
                mVideoView.stopPlayback();
            }
            if (player != null) {
                player.stop();
            }
            mVideoViewLayout.setVisibility(View.GONE);
            mAudioClosed.setVisibility(View.VISIBLE);
            mEnlargeBtn.setVisibility(View.GONE);
            mAudioName.setVisibility(View.VISIBLE);
            mAudioName.setText(video.getFilename());
            player = MediaPlayer.create(getContext(), uri);
            player.start();
            mSeekBar.setMax(player.getDuration());
            isPlaying = true;
        } else {
            if (player != null) {
                player.stop();
            }
            mVideoViewLayout.setVisibility(View.VISIBLE);
            mAudioClosed.setVisibility(View.GONE);
            mEnlargeBtn.setVisibility(View.VISIBLE);
            mAudioName.setVisibility(View.GONE);
            //设置视频路径
            mVideoView.setVideoURI(uri);
            //开始播放视频
            mVideoView.start();
            // 按照初始位置播放
            mVideoView.seekTo(0);
            mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    // 设置进度条的最大进度为视频流的最大播放时长
                    isPlaying = true;
                    mSeekBar.setMax(mVideoView.getDuration());
                    mActionBar.setImageDrawable(getContext().getResources().getDrawable(R.mipmap.ic_stop_bg));
                }
            });

            mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    // 在播放完毕被回调
                    isRePlaying = true;
                    mSeekBar.setProgress(0);
                    mActionBar.setImageDrawable(getContext().getResources().getDrawable(R.mipmap.ic_play_bg));
                }
            });
            mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    suspend();
                    return false;
                }
            });
        }
        startNewThread();
        HashMap<String, Object> filedata = new HashMap<>();
        filedata.put("fileid", video.getFileid());
        filedata.put("filename", video.getFilename());
        filedata.put("filetype", video.getFiletype());
        filedata.put("isconvert", video.getIsconvert());
        filedata.put("pagenum", video.getPagenum());
        filedata.put("swfpath", video.getSwfpath());

        HashMap<String, Object> data = new HashMap<>();
        data.put("filedata", filedata);
        data.put("fileid", video.getFileid());
        data.put("ismedia", true);
        data.put("page", 1);

        HashMap<String, Object> params = new HashMap<>();
        if ("audio".equals(mediaType)) {
            params.put("id", "Audio_MediaFilePage_ShowPage");
        } else {
            params.put("id", "Video_MediaFilePage_ShowPage");
        }
        params.put("name", "ShowPage");
        params.put("toID", "__allExceptSender");
        params.put("data", data);

        ClassRoomManager.getInstance().pubMsg(params);

        HashMap<String, Object> data1 = new HashMap<>();
        data1.put("action", 0);
        data1.put("currentTime", 0);
        data1.put("fileid", video.getFileid());
        data1.put("mediaType", mediaType);
        data1.put("play", true);

        HashMap<String, Object> params1 = new HashMap<>();
        params1.put("id", "MediaProgress_video_0");
        params1.put("name", "MediaProgress");
        params1.put("toID", "__allExceptSender");
        params1.put("data", data1);

        ClassRoomManager.getInstance().pubMsg(params1);
    }

    private void startNewThread() {
        new Thread() {
            @Override
            public void run() {
                try {
                    while (isPlaying) {
                        // 如果正在播放，每秒更新一次进度条
                        int current = 0;
                        if ("audio".equals(mediaType)) {
                            current = player.getCurrentPosition();
                        } else {
                            current = mVideoView.getCurrentPosition();
                        }
                        mSeekBar.setProgress(current);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTimeChangeTV.setText(stringForTime(mSeekBar.getProgress()) + "/" + stringForTime(mSeekBar.getMax()));
                            }
                        });
                        sleep(1000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private SeekBar.OnSeekBarChangeListener change = new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // 当进度条停止修改的时候触发
            // 取得当前进度条的刻度
            int progress = seekBar.getProgress();
            if ("audio".equals(mediaType)) {
                player.seekTo(progress);
            } else {
                if (mVideoView != null && mVideoView.isPlaying()) {
                    // 设置当前播放的位置
                    mVideoView.seekTo(progress);
                }
            }
            startNewThread();

            HashMap<String, Object> data = new HashMap<>();
            data.put("action", 1);
            data.put("currentTime", stringForSeconds(mSeekBar.getProgress()));
            data.put("fileid", video.getFileid());
            data.put("mediaType", mediaType);
            data.put("play", true);

            HashMap<String, Object> params = new HashMap<>();
            params.put("id", "MediaProgress_video_1");
            params.put("name", "MediaProgress");
            params.put("toID", "__allExceptSender");
            params.put("data", data);

            ClassRoomManager.getInstance().pubMsg(params);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

        }
    };

    //进度转时间
    private String stringForTime(int timeMs) {
        int totalSeconds = timeMs / 1000;

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;

        mFormatBuilder.setLength(0);
        if (hours > 0) {
            return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
        } else {
            return mFormatter.format("%02d:%02d", minutes, seconds).toString();
        }
    }

    //进度转秒
    private double stringForSeconds(int timeMs) {
        double totalSeconds = timeMs / 1000;
        DecimalFormat df = new DecimalFormat("######0.000000");
        return Double.parseDouble(df.format(totalSeconds));
    }

    /**
     * 送礼物信令
     *
     * @param peerId 收礼物人id   -1全部
     */
    private void givingGifts(String peerId) {
        mAnswerMsgLayout.setVisibility(View.GONE);
        mAnswerText.setVisibility(View.GONE);
        mAnswerImg.setVisibility(View.VISIBLE);
        mAnswerLayout.setVisibility(View.GONE);
        if (!TextUtils.isEmpty(peerId)) {
            Map<String, String> studios = new HashMap<>();
            if ("-1".equals(peerId)) {
                if (inClassUserList != null && inClassUserList.size() > 0) {
                    for (int i = 0; i < inClassUserList.size(); i++) {
                        studios.put(inClassUserList.get(i).getReceiveid(),
                                inClassUserList.get(i).getFirstname());
                    }
                }
            } else {
                studios.put(peerId, getOtherName(peerId));
            }
            mSendGiftPresenter.sendGift(serial, studios);
        }
    }

    /**
     * 显示送礼物提示框
     *
     * @param peerId 收礼物人id   -1全部
     */
    private void showGivingGifts(String peerId) {
        mAnswerMsgLayout.setVisibility(View.VISIBLE);
        mAnswerText.setVisibility(View.VISIBLE);
        mAnswerImg.setVisibility(View.GONE);
        mAnswerLayout.setVisibility(View.VISIBLE);
        mStartAnswer.setText("确定");
        mAnswerText.setText("提示");
        if (!TextUtils.isEmpty(peerId)) {
            if ("-1".equals(peerId)) {
                mAnswerMsg.setText("所有人");
            } else {
                mAnswerMsg.setText(getOtherName(peerId));
            }
        } else {
            givingGifts(peerId);
        }
    }

    @Override
    public void dissmiss(String type) {
        Log.e(TAG, "dissmiss:type: " + type);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mSendGiftsImg.setVisibility(View.VISIBLE);
                alphaAnimation2 = new TranslateAnimation(150f, 350f, 50, 50);
                alphaAnimation2.setDuration(3000);
                alphaAnimation2.setRepeatCount(Animation.INFINITE);
                alphaAnimation2.setRepeatMode(Animation.REVERSE);
                mSendGiftsImg.setAnimation(alphaAnimation2);
                alphaAnimation2.start();
                alphaAnimation2.cancel();
                mSendGiftsImg.setVisibility(View.GONE);
                if ("0".equals(type)) {
                    int giftNum = 0;
                    if (receiveGiftsId.equals("-1")) {//所有人
                        if (inClassUserList != null && inClassUserList.size() > 0) {
                            for (int i = 0; i < inClassUserList.size(); i++) {
                                giftNum = Integer.parseInt(inClassUserList.get(i).getGiftnum());
                                giftNum = giftNum + 1;
                                inClassUserList.get(i).setGiftnum(String.valueOf(giftNum));
                                HashMap<String, Object> property = new HashMap<>();
                                property.put("giftnumber", giftNum);
                                ClassRoomManager.getInstance().changeUserProperty(inClassUserList.get(i).getReceiveid(), "__all", property);
                            }
                        }
                    } else {
                        for (int i = 0; i < inClassUserList.size(); i++) {
                            if (receiveGiftsId.equals(inClassUserList.get(i).getReceiveid())) {
                                giftNum = Integer.parseInt(inClassUserList.get(i).getGiftnum());
                                giftNum = giftNum + 1;
                                inClassUserList.get(i).setGiftnum(String.valueOf(giftNum));
                                HashMap<String, Object> property = new HashMap<>();
                                property.put("giftnumber", giftNum);
                                ClassRoomManager.getInstance().changeUserProperty(receiveGiftsId, "__all", property);
                                return;
                            }
                        }
                    }
                } else {
                    Toast.makeText(TRoomActivityOne.this, "礼物发送失败", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

//===============白板========================

    //这个类中提供各种js可调用的方法。
    private class AndroidBridge {

        @JavascriptInterface
        public void sendBoardData(final String jsonStr) {
            System.out.println("jsonStrsend===========" + jsonStr);

            Gson gson = new Gson();
            HashMap message = new HashMap<>();
            message = gson.fromJson(jsonStr, message.getClass());

            String id = message.containsKey("id") ? message.get("id").toString() : "";
            String name = message.containsKey("signallingName") ? message.get("signallingName").toString() : "";
            String toID = message.containsKey("toID") ? message.get("toID").toString() : "";
            Object data = message.containsKey("data") ? message.get("data") : null;
            long seq = (message.containsKey("seq") && message.get("seq") instanceof Long) ? (Long) message.get("seq") : 0;
            long ts = (message.containsKey("ts") && message.get("ts") instanceof Long) ? (Long) message.get("ts") : 0;

            HashMap<String, Object> params = new HashMap<>();
            params.put("id", id);
            params.put("name", name);
            params.put("toID", toID);
            params.put("data", data);
            params.put("seq", seq);
            params.put("ts", ts);

            ClassRoomManager.getInstance().pubMsg(params);
        }

        @JavascriptInterface
        public void teacherTools(String data) {
            System.out.println("jsonStrsend===========" + data);
//            if (mAnswerLayout.getVisibility() == View.VISIBLE) {
//                return;
//            }
//            //判断用户单击的是那个超连接
//            String dice = "dice";
//            String answer = "answer";
//            String gift = "gift";
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    if (data.equals(dice)) {//掷骰子
//                        //这个超连接,java已经处理了，webview不要处理了
//                        mAnswerLayout.setVisibility(View.VISIBLE);
//                        answerOrPlay = "2";
//                        mAnswerMsgLayout.setVisibility(View.GONE);
//                        mAnswerText.setVisibility(View.GONE);
//                        mAnswerImg.setVisibility(View.VISIBLE);
//                        mAnswerImg.setImageDrawable(getContext().getResources().getDrawable(R.mipmap.ic_one));
//                        mStartAnswer.setText("开始掷骰子");
//                    } else if (data.equals(answer)) {//抢答
//                        mAnswerLayout.setVisibility(View.VISIBLE);
//                        answerOrPlay = "1";
//                        mAnswerMsgLayout.setVisibility(View.GONE);
//                        mAnswerText.setVisibility(View.GONE);
//                        mAnswerImg.setVisibility(View.VISIBLE);
//                        mAnswerImg.setImageDrawable(getContext().getResources().getDrawable(R.mipmap.ic_artboard));
//                        mStartAnswer.setText("开始抢答");
//                    } else if (data.equals(gift)) {//礼物
//                        answerOrPlay = "3";
//                        receiveGiftsId = "-1";
//                        showGivingGifts(receiveGiftsId);
//                    }
//                }
//            });
        }
    }

    //===============媒体========================
    @Override
    public void roomManagerRoomJoined() {
        Log.e(TAG, "roomManagerRoomJoined");
        JSONObject jsonObject = ClassRoomManager.getInstance().getRoomProperties();
        try {
            mTeacherName.setText(jsonObject.getString("firstname"));
            teacherId = jsonObject.getString("userid");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        allRoomUserList = ClassRoomManager.getInstance().getRoomUsers();
        mAdapter = new CommentListAdapter(new ArrayList<>(0), teacherId,
                mTeacherName.getText().toString());
        mCommList.setLayoutManager(new LinearLayoutManager(this));
        mCommList.setAdapter(mAdapter);

        AllRoomUser.RoomUser nowUser = new AllRoomUser.RoomUser(AllRoomUser.RoomUser.MSG);
        nowUser.setReceiveid(ClassRoomManager.getInstance().getMySelf().peerId);
        nowUser.setFirstname(ClassRoomManager.getInstance().getMySelf().nickName);
        nowUser.setState(0);
        nowUser.setTime(getTime());
        recUserList.add(nowUser);
        mAdapter.setNewData(recUserList);
        mCommList.scrollToPosition(mAdapter.getItemCount() - 1);
    }

    @Override
    public void roomManagerDidFinish() {
        Log.e(TAG, "roomManagerDidFinish: ");
        showPeerid = "";
        mTimeText.stop();
        if (CoursewareList != null && CoursewareList.size() > 0) {
            CoursewareList.clear();
        }
        if (VideoList != null && VideoList.size() > 0) {
            VideoList.clear();
        }
        if (inClassUserList != null && inClassUserList.size() > 0) {
            inClassUserList.clear();
        }
        if (inClassUserList != null && inClassUserList.size() > 0) {
            HashMap<String, Object> property = new HashMap<>();
            property.put("candraw", false);
            property.put("raisehand", false);
            ClassRoomManager.getInstance().changeUserProperty(inClassUserList.get(0).getReceiveid(), "__all", property);
            ClassRoomManager.getInstance().changeUserPublish(inClassUserList.get(0).getReceiveid(), 0);
        }
        this.finish();
    }

    @Override
    public void roomManagerUserJoined(ClassRoomUser user, boolean inList) {
        Log.e(TAG, "roomManagerUserJoined " + user.toString() + (inList ? " inlist" : ""));
        if (user.role == 0 && ClassRoomManager.getInstance().getMySelf().role == 0 ||
                (ClassRoomManager.getInstance().getRoomType() == 0 &&
                        user.role == ClassRoomManager.getInstance().getMySelf().role)) {
            ClassRoomManager.getInstance().evictUser(user.peerId);
        }

        showUserJoinedMessage(user);
        if (isClassBegin)
            ClassRoomManager.getInstance().reShow();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mStudentName.setText(getOtherName(user.peerId));
                if (!user.peerId.equals(ClassRoomManager.getInstance().getMySelf().peerId)) {
                    if (user.publishState == ClassRoomUser.PUBLISH_STATE_NONE) {
                        AllRoomUser.RoomUser nowUser = new AllRoomUser.RoomUser(AllRoomUser.RoomUser.MSG);
                        nowUser.setReceiveid(user.peerId);
                        nowUser.setFirstname(getOtherName(user.peerId));
                        nowUser.setState(user.publishState);
                        nowUser.setCandraw(user.canDraw);
                        nowUser.setGiftnum(user.giftnumber);
                        inClassUserList.add(nowUser);
                        mInClassAdapter.setNewData(inClassUserList);
                    }
                }
            }
        });

//        HashMap<String, Object> property = new HashMap<>();
//        property.put("candraw", false);
//        property.put("raisehand", false);
//        ClassRoomManager.getInstance().changeUserProperty(user.peerId, "__all", property);
//        ClassRoomManager.getInstance().changeUserPublish(user.peerId, 3);

    }

    private void showUserJoinedMessage(ClassRoomUser user) {
        boolean showComm = false;
        if (recUserList != null && recUserList.size() > 0) {
            for (int i = 0; i < recUserList.size(); i++) {
                if (user.peerId.equals(recUserList.get(i).getFirstname()) &&
                        valueOf(user.publishState).equals(valueOf(recUserList.get(i).getState()))) {
                    showComm = false;
                    break;
                } else {
                    showComm = true;
                }
            }
            if (showComm) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AllRoomUser.RoomUser nowUser = new AllRoomUser.RoomUser(AllRoomUser.RoomUser.MSG);
                        nowUser.setReceiveid(user.peerId);
                        nowUser.setFirstname(getOtherName(user.peerId));
                        nowUser.setState(user.publishState);
                        nowUser.setTime(getTime());
                        recUserList.add(nowUser);
                        mAdapter.setNewData(recUserList);
                        mCommList.scrollToPosition(mAdapter.getItemCount() - 1);
                    }
                });
            }
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    AllRoomUser.RoomUser nowUser = new AllRoomUser.RoomUser(AllRoomUser.RoomUser.MSG);
                    nowUser.setReceiveid(user.peerId);
                    nowUser.setFirstname(getOtherName(user.peerId));
                    nowUser.setState(user.publishState);
                    nowUser.setTime(getTime());
                    recUserList.add(nowUser);
                    mAdapter.setNewData(recUserList);
                    mCommList.scrollToPosition(mAdapter.getItemCount() - 1);
                }
            });
        }
    }

    private String getTime() {
        String time;
        Time t = new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone资料。
        t.setToNow(); // 取得系统时间。
        String hour = valueOf(t.hour);
        String minute;
        if (t.minute < 10) {
            minute = "0" + t.minute;
        } else {
            minute = valueOf(t.minute);
        }
        time = hour + ":" + minute;
        return time;
    }

    @Override
    public void roomManagerDidFailWithError(int error) {
        if (!isClassBegin) {
            ClassRoomManager.getInstance().set_status(0);
            finish();
        } else {
            ClassRoomManager.getInstance().delMsg("ClassBegin", "ClassBegin", "__all", null);
            ClassRoomManager.getInstance().leaveRoom();
        }
    }

    @Override
    public void roomManagerUserLeft(ClassRoomUser user) {//离开课堂
        Log.e(TAG, "roomManagerUserLeft " + user.toString());
        Log.e(TAG, "roomManagerUserLeft:inClassUserList:1 " + inClassUserList.toString());
        closeComaeMySelf(user.peerId);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!user.peerId.equals(ClassRoomManager.getInstance().getMySelf().peerId)) {
                    AllRoomUser.RoomUser nowUser = new AllRoomUser.RoomUser(AllRoomUser.RoomUser.MSG);
                    nowUser.setReceiveid(user.peerId);
                    nowUser.setFirstname(getOtherName(user.peerId));
                    nowUser.setState(-1);
                    nowUser.setTime(getTime());
                    recUserList.add(nowUser);
                    mAdapter.setNewData(recUserList);
                    mCommList.scrollToPosition(mAdapter.getItemCount() - 1);
                    HashMap<String, Object> property = new HashMap<>();
                    property.put("candraw", false);
                    property.put("raisehand", false);
                    ClassRoomManager.getInstance().changeUserProperty(user.peerId, "__all", property);
                    ClassRoomManager.getInstance().changeUserPublish(user.peerId, 0);
                }
                if (inClassUserList != null && inClassUserList.size() > 0) {
                    for (int i = 0; i < inClassUserList.size(); i++) {
                        if (user.peerId.equals(inClassUserList.get(i).getReceiveid())) {
                            showPeerid = null;
                            inClassUserList.remove(i);
                        }
                    }
                    mAdapter.setNewData(inClassUserList);
                    Log.e(TAG, "roomManagerUserLeft:inClassUserList:2 " + inClassUserList.toString());
                }
            }
        });
    }

    @Override
    public void roomManagerUserChanged(ClassRoomUser user) {
        Log.e(TAG, "roomManagerUserChanged " + user.toString());
        Log.e(TAG, "roomManagerUserChanged:inClassUserList:1 " + inClassUserList.toString());
        if (user.peerId.equals(ClassRoomManager.getInstance().getMySelf().peerId)) {
            if (user.publishState == 1) {//开启音频
                audioManager.setMicrophoneMute(false);
            } else if (user.publishState == 2) {//开启视频
                ClassRoomManager.getInstance().enableVideo(true);
            } else if (user.publishState == 3) {//开启音视频
                audioManager.setMicrophoneMute(false);
                ClassRoomManager.getInstance().enableVideo(true);
            } else if (user.publishState == 0) {//关闭音视频
                audioManager.setMicrophoneMute(true);
                ClassRoomManager.getInstance().enableVideo(false);
            }
        } else {
//            if (user.raiseHand) {
//                showHandUpDialog(user);
//            }
            if (inClassUserList != null && inClassUserList.size() > 0) {
                for (int i = 0; i < inClassUserList.size(); i++) {
                    if (user.peerId.equals(inClassUserList.get(i).getReceiveid())) {
                        user.giftnumber = inClassUserList.get(i).getGiftnum();
                    }
                }
            }
            Log.e(TAG, "roomManagerUserChanged: inClassUserList:" + inClassUserList.toString());
            if (inClassUserList != null && inClassUserList.size() > 0) {
                for (int i = 0; i < inClassUserList.size(); i++) {
                    if (user.peerId.equals(inClassUserList.get(i).getReceiveid())) {
                        Log.e(TAG, "roomManagerUserChanged:user.peerId: " + user.peerId);
                        AllRoomUser.RoomUser nowUser = inClassUserList.get(i);
                        nowUser.setReceiveid(user.peerId);
                        nowUser.setFirstname(getOtherName(user.peerId));
                        nowUser.setState(user.publishState);
                        nowUser.setCandraw(user.canDraw);
                        nowUser.setGiftnum(user.giftnumber);

                    }
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mAdapter.setNewData(inClassUserList);
                        mInClassAdapter.notifyDataSetChanged();
                        Log.e(TAG, "roomManagerUserChanged:inClassUserList:1 " + inClassUserList.toString());
                    }
                });
            }
        }
    }

    /**
     * 举手提示框
     *
     * @param user
     */
    private void showHandUpDialog(ClassRoomUser user) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                AllRoomUser.RoomUser nowUser = new AllRoomUser.RoomUser(AllRoomUser.RoomUser.HSP);
                nowUser.setReceiveid(user.peerId);
                nowUser.setFirstname(getOtherName(user.peerId));
                nowUser.setState(0);
                nowUser.setTime(getTime());
                nowUser.setShow(true);
                nowUser.setHeadup(false);
                recUserList.add(nowUser);
                mAdapter.setNewData(recUserList);
                mCommList.scrollToPosition(mAdapter.getItemCount() - 1);
            }
        });


//        AlertDialog.Builder builder = new AlertDialog.Builder(TRoomActivity.this);
//        View view = LayoutInflater.from(TRoomActivity.this).inflate(R.layout.dialog_signin, null);
//        TextView mDisagree = (TextView) view.findViewById(R.id.disagree);
//        TextView mAgree = (TextView) view.findViewById(R.id.agree);
//        TextView mUserName = (TextView) view.findViewById(R.id.user_name);
//        mUserName.setText(getOtherName(user.peerId));
//        mDisagree.setOnClickListener(v -> {
//
//            alertDialog.dismiss();
//        });
//        mAgree.setOnClickListener(v -> {
//            HashMap<String, Object> property = new HashMap<>();
//            property.put("publishstate", 3);
//            property.put("raisehand", false);
//            ClassRoomManager.getInstance().changeUserProperty(user.peerId, "__all", property);
//            alertDialog.dismiss();
//        });
//        builder.setView(view);
//        alertDialog = builder.show();
//        Window dialogWindow = alertDialog.getWindow();
//        WindowManager m = this.getWindowManager();
//        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
//        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
//        p.height = (int) (d.getHeight() * 0.4); // 高度设置为屏幕的0.4，根据实际情况调整
//        p.width = (int) (d.getWidth() * 0.2); // 宽度设置为屏幕的0.2，根据实际情况调整
//        dialogWindow.setAttributes(p);
    }

    private void closeComaeMySelf(String peerId) {
        mSurfaceViewStudent.release();
    }

    @Override
    public Object roomManagerUserVideoPublished(String peerId) {
        Log.e(TAG, "roomManagerUserVideoPublished " + peerId);
        if (TextUtils.isEmpty(showPeerid)) {
            showPeerid = peerId;
            mSurfaceViewStudent.init(EglBase.create().getEglBaseContext(), null);
            return mSurfaceViewStudent;
        }
        return null;
    }

    private String getOtherName(String peerId) {
        String name;
        for (int i = 0; i < allRoomUserList.size(); i++) {
            if (peerId.equals(allRoomUserList.get(i).getReceiveid())) {
                name = allRoomUserList.get(i).getFirstname();
                return name;
            }
        }
        return null;
    }

    private String getOtherGift(String peerId) {
        String gift;
        for (int i = 0; i < inClassUserList.size(); i++) {
            if (peerId.equals(inClassUserList.get(i).getReceiveid())) {
                gift = inClassUserList.get(i).getGiftnum();
                return gift;
            }
        }
        return null;
    }

    @Override
    public void roomManagerUserVideoUnPublished(String peerId) {
        Log.e(TAG, "roomManagerUserVideoUnPublished " + peerId);
        if (peerId.equals(LifeApplication.getInstance().getCurrentUser().getUserid())) {
            mSurfaceViewTeacher.release();
        }

    }

    @Override
    public void roomManagerIceStatusChanged(String peerId, String state) {
        Log.e(TAG, "roomManagerIceStatusChanged " + state + " " + peerId);
    }

    @Override
    public void roomManagerMessageReceived(String peerId, String message) {
        Log.e(TAG, "roomManagerMessageReceived " + peerId);
        if (!TextUtils.isEmpty(peerId) && allRoomUserList != null && allRoomUserList.size() > 0) {
            String receivedName = null;

            for (int i = 0; i < allRoomUserList.size(); i++) {
                Log.e(TAG, "roomManagerMessageReceived:getReceiveid " + allRoomUserList.get(i).getReceiveid());
                Log.e(TAG, "roomManagerMessageReceived:getSendid " + allRoomUserList.get(i).getSendid());
                Log.e(TAG, "roomManagerMessageReceived:getAccount " + allRoomUserList.get(i).getAccount());
                if (peerId.equals(allRoomUserList.get(i).getReceiveid())) {
                    receivedName = allRoomUserList.get(i).getFirstname();
                    break;
                } else if (peerId.equals(allRoomUserList.get(i).getSendid())) {
                    receivedName = mTeacherName.getText().toString().trim();
                    break;
                } else if (peerId.equals(LifeApplication.getInstance().getCurrentUser().getUserid())) {
                    receivedName = LifeApplication.getInstance().getCurrentUser().getFirstname();
                    break;
                }
            }
            if (!TextUtils.isEmpty(receivedName)) {
                String finalReceivedName = receivedName;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AllRoomUser.RoomUser user = new AllRoomUser.RoomUser(AllRoomUser.RoomUser.COM);
                        user.setFirstname(finalReceivedName);
                        user.setReceiveid(peerId);
                        user.setMessage(message);
                        user.setTime(getTime());
                        user.setState(-1);
                        recUserList.add(user);
                        mAdapter.setNewData(recUserList);
                        mCommList.scrollToPosition(mAdapter.getItemCount() - 1);
                        mSayEdt.setText("");
                    }
                });

            }
        }
    }

    @Override
    public void roomManagerOnRemoteMsg(boolean add, String id, String name, String fromWhom, long ts, Object data) {
        Log.e(TAG, "roomManagerOnRemoteMsg " + "add:" + add + "-id:" + id + "-name:" + name + " data: " + data);

        if (name.equals("ClassBegin")) {
            if (add) { // class begins
                Log.e(TAG, "class begins");
                isClassBegin = true;
                classStarTime = ts;
                ClassRoomManager.getInstance().pubMsg("UpdateTime", "UpdateTime",
                        ClassRoomManager.getInstance().getMySelf().peerId, null);
//                ClassRoomManager.getInstance().changeUserPublish(ClassRoomManager.getInstance().getMySelf().peerId, 3);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mUpHeadBtn.setText("结束课程");
                        dismissLoadDialog();
                    }
                });
                if (data != null) {
                    Gson gson = new Gson();
                    HashMap message = new HashMap<>();
                    message = gson.fromJson(data.toString(), message.getClass());
                    Map mediaProgress1 = message.containsKey("MediaProgress_video_1") ? (Map) message.get("MediaProgress_video_1") : null;
                    Map mediaProgress0 = message.containsKey("MediaProgress_video_0") ? (Map) message.get("MediaProgress_video_0") : null;
                    Map mediaProgressShowPage = message.containsKey("Video_MediaFilePage_ShowPage") ? (Map) message.get("Video_MediaFilePage_ShowPage") : null;
                    Map audioProgressShowPage = message.containsKey("Audio_MediaFilePage_ShowPage") ? (Map) message.get("Audio_MediaFilePage_ShowPage") : null;
                    if (mediaProgress0 != null) {
                        Map audioProgressShowPageDetail = null;
                        Map mediaProgressShowPageDetail = null;
                        Map mediaProgress1Detail = null;
                        Map mediaProgress0Detail = (Map) mediaProgress0.get("data");
                        if (mediaProgressShowPage != null) {
                            mediaProgressShowPageDetail = (Map) mediaProgressShowPage.get("data");
                        }
                        if (mediaProgress1 != null) {
                            mediaProgress1Detail = (Map) mediaProgress1.get("data");
                        }
                        if (audioProgressShowPage != null) {
                            audioProgressShowPageDetail = (Map) audioProgressShowPage.get("data");
                        }
                        Map fileDate = null;
                        if (mediaProgressShowPageDetail != null) {
                            fileDate = mediaProgressShowPageDetail.containsKey("filedata") ? (Map) mediaProgressShowPageDetail.get("filedata") : null;
                        } else if (audioProgressShowPageDetail != null) {
                            fileDate = audioProgressShowPageDetail.containsKey("filedata") ? (Map) audioProgressShowPageDetail.get("filedata") : null;
                        }
                        if (fileDate != null) {
                            mediaType = (String) fileDate.get("filetype");
                            String path = (String) fileDate.get("swfpath");
                            String filename = (String) fileDate.get("filename");
                            Object fileid = fileDate.containsKey("fileid") ? fileDate.get("fileid") : null;
                            if (mediaType.equals("mp4") || mediaType.equals("webm")) {
                                mediaType = "video";
                            } else if (mediaType.equals("mp3") || mediaType.equals("wav") || mediaType.equals("ogg")) {
                                mediaType = "audio";
                            }
                            String fileID = "";
                            if (fileid != null) {
                                if (fileid instanceof String) {
                                    fileID = fileid.toString();
                                    if (fileID.contains(".")) {
                                        String[] strarray = fileID.split("\\.");
                                        fileID = strarray[0];
                                    } else if (fileid instanceof Double) {
                                        double num = (double) fileid;
                                        int _id = (int) num;
                                        fileID = String.valueOf(_id);
                                    }
                                }
                            }
                            if (!TextUtils.isEmpty(fileID)) {
                                video = new RoomFile();
                                video.setState("0");
                                video.setPagenum("1");
                                video.setIsconvert("1");
                                video.setFiletype(mediaType);
                                video.setFilename(filename);
                                video.setSwfpath(path);
                                video.setFileid(fileID);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        showVideoView(video);//打开视频
                                    }
                                });
                                HashMap<String, Object> object = new HashMap<>();
                                object.put("filedata", fileDate);
                                object.put("fileid", video.getFileid());
                                object.put("ismedia", true);
                                object.put("page", 1);

                                HashMap<String, Object> params = new HashMap<>();
                                if ("audio".equals(mediaType)) {
                                    params.put("id", "Audio_MediaFilePage_ShowPage");
                                } else {
                                    params.put("id", "Video_MediaFilePage_ShowPage");
                                }
                                params.put("name", "ShowPage");
                                params.put("toID", "__allExceptSender");
                                params.put("data", object);

                                ClassRoomManager.getInstance().pubMsg(params);
                            }
                        }
                        boolean play = true;
                        if (mediaProgress0Detail != null) {
                            Object playType = mediaProgress0Detail.containsKey("play") ? mediaProgress0Detail.get("play") : null;
                            Object currentTime = mediaProgress0Detail.containsKey("currentTime") ? mediaProgress0Detail.get("currentTime") : null;
                            mediaType = mediaProgress0Detail.containsKey("mediaType") ? (String) mediaProgress0Detail.get("mediaType") : "";
                            int time = 0;
                            if (currentTime != null) {
                                String timeStr = currentTime.toString();
                                if (timeStr.contains(".")) {
                                    String[] strarray = timeStr.split("\\.");
                                    time = Integer.valueOf(strarray[0]);
                                }
                            }
                            time = time * 1000;
                            String dataType = "";
                            if (playType != null) {
                                if (playType instanceof String) {
                                    dataType = (String) playType;
                                } else if (playType instanceof Boolean) {
                                    play = (Boolean) playType;
                                }
                                if ("1".equals(dataType)) {
                                    play = true;
                                }
                            }
                            if (play) {
                                pause(time);
                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        suspend();
                                    }
                                });
                            }
                            HashMap<String, Object> params = new HashMap<>();
                            params.put("id", "MediaProgress_video_0");
                            params.put("name", "MediaProgress");
                            params.put("toID", "__allExceptSender");
                            params.put("data", mediaProgress0Detail);
                            ClassRoomManager.getInstance().pubMsg(params);
                        }
                        if (mediaProgress1Detail != null) {
                            Object currentTime = mediaProgress1Detail.containsKey("currentTime") ? mediaProgress1Detail.get("currentTime") : null;
                            mediaType = mediaProgress1Detail.containsKey("mediaType") ? (String) mediaProgress1Detail.get("mediaType") : "";
                            int time = 0;
                            if (currentTime != null) {
                                String timeStr = currentTime.toString();
                                if (timeStr.contains(".")) {
                                    String[] strarray = timeStr.split("\\.");
                                    time = Integer.valueOf(strarray[0]);
                                } else {
                                    time = Integer.valueOf(timeStr);
                                }
                            }
                            time = time * 1000;
                            if (play) {
                                pause(time);
                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        suspend();
                                    }
                                });
                            }
                            HashMap<String, Object> params = new HashMap<>();
                            params.put("id", "MediaProgress_video_1");
                            params.put("name", "MediaProgress");
                            params.put("toID", "__allExceptSender");
                            params.put("data", mediaProgress1Detail);

                            ClassRoomManager.getInstance().pubMsg(params);
                        }
                    }
                }
            } else { // class end
                Log.d(TAG, "class ends");
                isClassBegin = false;
                localTime = 0;
                ClassRoomManager.getInstance().changeUserPublish(ClassRoomManager.getInstance().getMySelf().peerId, 0);
                ClassRoomManager.getInstance().leaveRoom();
            }
        } else if (name.equals("UpdateTime")) {
            if (add) {
                if (isClassBegin) {
                    if (seveiceTime != ts) {
                        seveiceTime = ts;
                        localTime = seveiceTime - classStarTime;
                        Log.d(TAG, "localTime====" + localTime);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //设置初始值（重置）
                                mTimeText.setBase(SystemClock.elapsedRealtime() - localTime * 1000);//计时器清零
                                int hour = (int) ((SystemClock.elapsedRealtime() - mTimeText.getBase()) / 1000 / 3600);
                                if (hour > 0) {
                                    mTimeText.setFormat("0" + "%s");
                                } else {
                                    mTimeText.setFormat("0" + valueOf(hour) + ":%s");
                                }
                                mTimeText.start();
                            }
                        });
                    }
                }
            }
        } else if (name.equals("playDice")) {//掷骰子
            if (add) {
                Gson gson = new Gson();
                HashMap message = new HashMap<>();
                message = gson.fromJson(data.toString(), message.getClass());
                boolean isShowDice = message.containsKey("isShowDice") ? (boolean) message.get("isShowDice") : false;
                ArrayList<Object> playList = message.containsKey("stus") ? (ArrayList<Object>) message.get("stus") : null;
                if (isShowDice && playList != null) {//开始摇色子
//                    showPlayDice(playList);
                } else {//停止摇骰子
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mAnswerLayout.setVisibility(View.GONE);
                        }
                    });

                }
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mAnswerLayout.setVisibility(View.GONE);
                    }
                });
            }
        } else if (name.equals("stopAnswer")) {//抢答结束
            showMessage("抢答结束，本轮无人抢答");
        } else if (name.equals("answer")) {//有人已抢答
            Gson gson = new Gson();
            HashMap message = new HashMap<>();
            message = gson.fromJson(data.toString(), message.getClass());
            String username = message.containsKey("username") ? message.get("username").toString() : "";
            showMessage("优胜者为:".concat(username));
        } else if (TextUtils.isEmpty(name)) {
            if (isClassBegin) {
                ClassRoomManager.getInstance().set_status(0);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (CoursewareList != null && CoursewareList.size() > 0) {
                            CoursewareList.clear();
                        }
                        if (VideoList != null && VideoList.size() > 0) {
                            VideoList.clear();
                        }
                        if (inClassUserList != null && inClassUserList.size() > 0) {
                            inClassUserList.clear();
                        }
                        Toast.makeText(TRoomActivityOne.this, "开启课堂失败，请再次点击上课按钮", Toast.LENGTH_SHORT).show();

                    }
                });
            }
            dismissLoadDialog();
            isClassBegin = false;
            return;
        }
        if (data != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if ("0".equals(fromWhom)) {
                        Log.d(TAG, "roomManagerOnRemoteMsgUrl: " + "javascript:GLOBAL.phone.receivePhoneByTriggerEvent(" + "\"message-list-received\"" + ", " + data + ")");
                        mShowView.loadUrl("javascript:GLOBAL.phone.receivePhoneByTriggerEvent(" + "\"message-list-received\"" + ", " + data + ")");
                    } else if ("1".equals(fromWhom)) {
                        JSONObject nowData = new JSONObject();
                        if (add) {
                            try {
                                nowData.put("id", id);
                                nowData.put("name", name);
                                nowData.put("ts", ts);
                                nowData.put("data", data);
                                if (nowData.getString("data") != null) {
                                    Log.d(TAG, "roomManagerOnRemoteMsgUrl: " + "javascript:GLOBAL.phone.receivePhoneByTriggerEvent(" + "\"publish-message-received\"" + ", " + nowData + ")");
                                    mShowView.loadUrl("javascript:GLOBAL.phone.receivePhoneByTriggerEvent(" + "\"publish-message-received\"" + ", " + nowData + ")");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            Log.d(TAG, "roomManagerOnRemoteMsgUrl: " + "javascript:GLOBAL.phone.receivePhoneByTriggerEvent(" + "\"delete-message-received\"" + ", " + data + ")");
                            mShowView.loadUrl("javascript:GLOBAL.phone.receivePhoneByTriggerEvent(" + "\"delete-message-received\"" + ", " + data + ")");
                        }

                    }
                }
            });
        }
    }

    private void showPlayDice(ArrayList<Object> playList) {


    }

    private void showView(ImageView mPlayImg, String num) {
        Log.d(TAG, "showView: num==========" + num);
        int number = 0;
        if (num.contains(".")) {
            int idx = num.lastIndexOf(".");//查找小数点的位置
            String strNum = num.substring(0, idx);//截取从字符串开始到小数点位置的字符串，就是整数部分
            number = Integer.valueOf(strNum);//把整数部分通过Integer.valueof方法转换为数字
        } else {
            number = Integer.valueOf(num);
        }
        int finalNumber = number;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mStartAnswer.setEnabled(true);
                mPlayImg.setVisibility(View.VISIBLE);
                AnimationDrawable frameAnim = (AnimationDrawable) getResources().getDrawable(R.drawable.bullet_anim);
                mPlayImg.setBackgroundDrawable(frameAnim);
                frameAnim.start();
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        //execute the task
                        frameAnim.stop();
                        switch (finalNumber) {//显示筛子数字
                            case 1:
                                mPlayImg.setBackgroundResource(R.mipmap.ic_one);
                                break;
                            case 2:
                                mPlayImg.setBackgroundResource(R.mipmap.ic_two);
                                break;
                            case 3:
                                mPlayImg.setBackgroundResource(R.mipmap.ic_three);
                                break;
                            case 4:
                                mPlayImg.setBackgroundResource(R.mipmap.ic_four);
                                break;
                            case 5:
                                mPlayImg.setBackgroundResource(R.mipmap.ic_five);
                                break;
                            case 6:
                                mPlayImg.setBackgroundResource(R.mipmap.ic_six);
                                break;
                        }
                    }
                }, 3000);
            }
        });

    }

    private void showMessage(String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mStartAnswer.setEnabled(true);
                mAnswerLayout.setVisibility(View.VISIBLE);
                mAnswerImg.setVisibility(View.GONE);
                mAnswerText.setVisibility(View.VISIBLE);
                mAnswerText.setText(message);
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        //execute the task
                        mAnswerLayout.setVisibility(View.GONE);
                        mAnswerImg.setVisibility(View.VISIBLE);
                        mAnswerText.setVisibility(View.GONE);
                    }
                }, 3000);
            }
        });
    }

    @Override
    public void roomGiftInfo(String num) {

    }

    @Override
    public void roomFileInfo(List<RoomFile> list) {
        for (int i = 0; i < list.size(); i++) {
            String fileType = list.get(i).getFiletype();
            if (fileType.equals("jpg") || fileType.equals("jpeg") || fileType.equals("png")
                    || fileType.equals("gif") || fileType.equals("bmp")) {
                CoursewareList.add(list.get(i));
            } else if (fileType.equals("doc") || fileType.equals("docx")) {
                CoursewareList.add(list.get(i));
            } else if (fileType.equals("pdf")) {
                CoursewareList.add(list.get(i));
            } else if (fileType.equals("ppt") || fileType.equals("pptx")) {
                CoursewareList.add(list.get(i));
            } else if (fileType.equals("txt")) {
                CoursewareList.add(list.get(i));
            } else if (fileType.equals("xls") || fileType.equals("xlsx")) {
                CoursewareList.add(list.get(i));
            } else if (fileType.equals("mp4") || fileType.equals("webm")) {
                VideoList.add(list.get(i));
            } else if (fileType.equals("mp3") || fileType.equals("wav") || fileType.equals("ogg")) {
                VideoList.add(list.get(i));
            }
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mCoursewareAdapter.setNewData(CoursewareList);
                mCoursewareTitle.setText("课件列表(".concat(valueOf(CoursewareList.size()).concat(")")));
                mVideoAdapter.setNewData(VideoList);
                mVideoTitle.setText("媒体列表(".concat(valueOf(VideoList.size()).concat(")")));
            }
        });
    }

    @Override
    public void participantEvicted(ClassRoomUser myself) {
        if (myself.peerId.equals(LifeApplication.getInstance().getCurrentUser().getUserid()) && isClassBegin) {
            showClosedDialog();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isClassBegin) {
                ClassRoomManager.getInstance().set_status(0);
                finish();
            } else {
                showLeaveDialog();
            }
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private void showLeaveDialog() {
        final AlertDialog.Builder normalDialog = new AlertDialog.Builder(this);
        normalDialog.setTitle("退出课堂");
        normalDialog.setMessage("课程进行中，是否要退出课堂?");
        normalDialog.setPositiveButton("是", (dialog, which) -> {
            dialog.dismiss();
            ClassRoomManager.getInstance().delMsg("ClassBegin", "ClassBegin", "__all", null);
            ClassRoomManager.getInstance().leaveRoom();
        });
        normalDialog.setNegativeButton("否", (dialog, which) -> dialog.dismiss());
        // 显示
        normalDialog.show();
    }

    private void showClosedDialog() {
        final AlertDialog.Builder normalDialog = new AlertDialog.Builder(this);
        normalDialog.setTitle("退出课堂");
        normalDialog.setMessage("有相同账号进入课堂，您将离开此课堂");
        normalDialog.setCancelable(false);
        normalDialog.setPositiveButton("确定", (dialog, which) -> {
//            ClassRoomManager.getInstance().delMsg("ClassBegin", "ClassBegin", "__all", null);
//            ClassRoomManager.getInstance().leaveRoom();
            dialog.dismiss();
            finish();
            LifeApplication.getInstance().outOffSuccess(this);
        });
        normalDialog.show();
    }
}
